<?php

namespace app\controllers\admin\uni\role;

use app\controllers\admin\base\AdminController;
use app\models\role\RoleMenu as Model;
use yii\db\Exception;

class MenuController extends AdminController
{
    public function actionList()
    {
        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $query = Model::find();

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->asArray()
            ->all();

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    public function actionEdit()
    {
        $data = $this->post();

        try {
            if (isset($data['id']) && $data['id'] > 0) {
                $model = Model::findOne(['id' => $data['id']]);
                if (!$model) {
                    return $this->fail('操作失败');
                }
            } else {
                $model = new Model();
            }
            $data = ['RoleMenu' => $data];
            if ($model->load($data) && $model->save()) {
                return $this->success($model, '操作成功');
            } else {
                throw new Exception($model->getFirstError('url'));
            }
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionView()
    {
        $id = $this->post('id');
        $model = Model::find()
            ->where(['id' => $id])
            ->asArray()
            ->one();

        if ($model) {
            return $this->success($model);
        }

        return $this->fail('不存在该菜单');
    }

    public function actionRemove()
    {
        $id = $this->post('id');

        try {
            $model = Model::findOne(['id' => $id]);

            if ($model->delete()) {
                return $this->success($model, '删除成功');
            }
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }


}